package com.zixuan.sina.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.zixuan.sina.dao.PostLikeMapper;
import com.zixuan.sina.dao.PostMapper;
import com.zixuan.sina.entity.Post;
import com.zixuan.sina.entity.PostLike;
import com.zixuan.sina.entity.Topic;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.entity.vo.*;
import com.zixuan.sina.service.CommentService;
import com.zixuan.sina.service.PostService;
import com.zixuan.sina.service.TopicService;
import com.zixuan.sina.service.UserService;
import com.zixuan.sina.utils.DateComputeUtils;
import com.zixuan.sina.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Resource
    private PostLikeMapper postLikeMapper;
    @Resource
    private UserService userService;
    @Resource
    private TopicService topicService;

    @Resource
    private CommentService commentService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Result<List<PostVo>> listPost() {
        List<PostVo> result = new ArrayList<>();

        List<Post> list = this.list();
        list=list.stream().filter(f->f.getIsShow()==0).collect(Collectors.toList());
        for (Post post : list) {
            PostVo postVo = new PostVo();
            BeanUtils.copyProperties(post, postVo);
            String imgUrl = post.getImgUrl();
            if (imgUrl != null) {
                String[] imgUrlSplit = imgUrl.split(",");
                List<String> imgs = new ArrayList<>();
                for (String img : imgUrlSplit) {
                    if (!StringUtils.isEmpty(img)) {
                        imgs.add(img);
                    }

                }
                postVo.setImgUrls(imgs);
            }

            String videoUrl = post.getVideoUrl();
            if (videoUrl != null) {
                String[] videoUrlSplit = videoUrl.split(",");
                List<String> videos = new ArrayList<>();
                for (String video : videoUrlSplit) {
                    if (!StringUtils.isEmpty(video)) {
                        videos.add(video);
                    }

                }
                postVo.setVideoUrls(videos);
            }


            User user = userService.findUserById(post.getUserId());
            BeanUtils.copyProperties(user, postVo);
            String between = DateComputeUtils.between(new Date(), post.getPostTime());
            postVo.setDisplayText(between);
            //查询话题信息
            List<Topic> topics = topicService.getTopicsByPostId(postVo.getPostId());


            List<String> topicStr = new ArrayList<>();
            for (Topic topic : topics) {
                if (null != topic) {
                    String temp = topic.getTopicStr();
                    if (null != temp) {
                        temp = "#" + temp + "#";
                        topicStr.add(temp);
                    }
                }


            }
            postVo.setTopics(topicStr);
            result.add(postVo);
        }
        return Result.ok(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(PostRequestAdd post) {
        String message="";
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String id = principal.getId();
        post.setUserId(id);
        Post postSave = new Post();
        BeanUtils.copyProperties(post, postSave);
        String content = postSave.getContent();
        //todo:此处对于用户所输入的关键字提取还有问题
        if (content.contains("#")) {
            int index = content.lastIndexOf("# ");
            if (index != -1) {
                content = content.substring(index + 1, content.length());
            }
        }

        postSave.setContent(content);
        postSave.setTitle(post.getTitle());
        List<String> words = approvalPost(postSave.getContent());
        if(!CollectionUtil.isEmpty(words)){
            postSave.setReasion("包含敏感词:"+words.toString());
            postSave.setIsShow(1);
            message="文章发布失败,包含敏感词："+words.toString();
        }
        boolean save = this.save(postSave);
        String postId = postSave.getPostId();
        //todo:添加话题信息
        List<Long> topicIds = post.getTopicIds();
        if (ObjectUtil.isNotNull(topicIds)) {
            topicService.addPostTopic(postId, topicIds);
        }


        if (!save) {
            return Result.error().message("发布文章失败");
        }

        return Result.ok(message);
    }

    @Override
    public Result<List<PostVo>> queryPost(PostQuery postQuery) {
        if (!ObjectUtil.isEmpty(postQuery)) {
            List<PostVo> result = new ArrayList<>();
            List<PostVo> postVos = baseMapper.queryPost(postQuery);
            List<String> collect = postVos.stream().map(m -> m.getUserId()).collect(Collectors.toList());
            Map<String, User> map = collect.stream().map(m -> {
                User user = userService.findUserById(m);
                return user;
            }).collect(Collectors.toMap(User::getId, each -> each, (value1, value2) -> value1));
            for (PostVo postVo : postVos) {
                User user = map.get(postVo.getUserId());
                if(user!=null){
                    postVo.setId(Long.valueOf(user.getId()));
                    postVo.setRealName(user.getRealName());
                    postVo.setNickName(user.getNickName());
                    postVo.setGender(user.getGender());
                    postVo.setPhone(user.getPhone());
                    postVo.setEmail(user.getEmail());
                    postVo.setAvatar(user.getAvatar());
                }

            }
            result = getPostVoResult(postVos);
            return Result.ok(result);
        }
        return Result.error();
    }



    public  PostLikeVo  getPostLikeInfo(String postId){
        //1.  当前文章的点赞数
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal==null){
            throw new RuntimeException("请登录后尝试");
        }
        String id = principal.getId();
        LambdaQueryWrapper<PostLike> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(PostLike::getPostId,postId);
        Long count = postLikeMapper.selectCount(wrapper);
        //2.当前用户是否给当前文章点赞
        wrapper.eq(PostLike::getUserId,id);
        PostLike postLike = postLikeMapper.selectOne(wrapper);
        boolean isLike=false;
        if(postLike!=null){
         isLike=true;
        }
        PostLikeVo postLikeVo = new PostLikeVo();
        postLikeVo.setLikeNum(count);
        postLikeVo.setLiked(isLike);
        return postLikeVo;

    }
    /**
     *
     * @param postVos
     * @param
     * @param
     * @param
     * @return
     */
    public  List<PostVo> getPostVoResult(List<PostVo> postVos) {
        List<PostVo> result = new ArrayList<>();
        for (PostVo post : postVos) {
            PostVo postVo = new PostVo();
            BeanUtils.copyProperties(post, postVo);
            String imgUrl = post.getImgUrl();
            if (imgUrl != null) {
                String[] imgUrlSplit = imgUrl.split(",");
                List<String> imgs = new ArrayList<>();
                for (String img : imgUrlSplit) {
                    if (!StringUtils.isEmpty(img)) {
                        imgs.add(img);
                    }

                }
                postVo.setImgUrls(imgs);
            }

            String videoUrl = post.getVideoUrl();
            if (videoUrl != null) {
                String[] videoUrlSplit = videoUrl.split(",");
                List<String> videos = new ArrayList<>();
                for (String video : videoUrlSplit) {
                    if (!StringUtils.isEmpty(video)) {
                        videos.add(video);
                    }

                }
                postVo.setVideoUrls(videos);
            }
            User user = userService.findUserById(post.getUserId());
            BeanUtils.copyProperties(user, postVo);
            String between = DateComputeUtils.between(new Date(), post.getPostTime());
            postVo.setDisplayText(between);
            //查询话题信息
            List<Topic> topics = topicService.getTopicsByPostId(postVo.getPostId());


            List<String> topicStr = new ArrayList<>();
            for (Topic topic : topics) {
                if (null != topic) {
                    String temp = topic.getTopicStr();
                    if (null != temp) {
                        temp = "#" + temp + "#";
                        topicStr.add(temp);
                    }
                }


            }
            postVo.setTopics(topicStr);
            List<CommentVo> commentVos = commentService.listComment(postVo.getPostId());
            postVo.setCommentVos(commentVos);
            //查询文章点赞记录
            PostLikeVo postLikeInfo = getPostLikeInfo(postVo.getPostId());
            postVo.setLikeNum(postLikeInfo.getLikeNum());
            postVo.setLiked(postLikeInfo.isLiked());
            result.add(postVo);
        }
        return result;

    }


    @Override
    public Result updatePost(Post post) {
        List<String> words = approvalPost(post.getContent());
        String message="";
        if(!CollectionUtil.isEmpty(words)){
            post.setReasion("包含敏感词:"+words.toString());
            post.setIsShow(1);
            message="文章发布失败,包含敏感词："+words.toString();
        }
        int row = baseMapper.updateById(post);
        return Result.ok(message);
    }

    @Override
    public Result listVideo(String key, String type, String userId, String startTime, String endTime) {
        PostQuery videoQuery = new PostQuery();
        videoQuery.setKey(key);
        videoQuery.setType(type);
//        videoQuery.setStartTime(startTime);
//        videoQuery.setEndTime(endTime);
        videoQuery.setUserId(userId);
        List<PostVo> postVos = baseMapper.queryVideo(videoQuery);
        List<PostVo> postVoResult = getPostVoResult(postVos);
        return Result.ok().data(postVoResult);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result thumbStar(List<String> postIds) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null == principal) {
            throw new AccountExpiredException("未登录无权限操作");
        }
        redisTemplate.opsForHash().put("starValue",principal.getId(),postIds);

        return Result.ok().message("操作成功");
    }

    @Override
    public Result setSpecial(String postId) {
        QueryWrapper<Post> wrapper = new QueryWrapper<>();
        Post post = baseMapper.selectOne(wrapper.eq("post_id", postId));
        int isSpecial = post.getIsSpecial();
        if(isSpecial==0){
            post.setIsSpecial(1);
        }else {
            post.setIsSpecial(0);
        }
        baseMapper.updateById(post);
        return Result.ok();
    }

    @Override
    public Result getPost(String postId) {
        Post post = baseMapper.selectById(postId);
        return Result.ok(post);
    }

    @Override
    public Result<List<PostMangerVo>> getViolationPost(String keyword) {
        LambdaQueryWrapper<Post> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Post::getIsShow,1);
        if(StrUtil.isNotBlank(keyword)){
            wrapper.eq(Post::getContent,keyword).or().eq(Post::getTitle,keyword);
        }
        List<Post> posts = baseMapper.selectList(wrapper);
        //根据userId查出用户昵称
        List<PostMangerVo> collect = posts.stream().map(m -> {
            PostMangerVo postMangerVo = new PostMangerVo();
            BeanUtil.copyProperties(m, postMangerVo);
            String userId = m.getUserId();
            User userById = userService.findUserById(userId);
            if (ObjectUtil.isNotNull(userById)) {
                postMangerVo.setNickName(userById.getNickName());
            }
            return postMangerVo;
        }).collect(Collectors.toList());
        return Result.ok(collect);
    }

    @Override
    public Result deletePost(String postId) {
        int row = baseMapper.deleteById(postId);
        return row>0 ? Result.ok() : Result.error();
    }

    public List<String> approvalPost(String content){
        List<String> wordList = SensitiveWordHelper.findAll(content);
        return wordList;
    }
}
